import base64
import json
import pickle

from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.address.models import Address
from apps.goods.models import FoodsChannel
from utils import constants
from utils.response_code import RETCODE


class CartsView(View):
    def get(self,request):
        """展示购物车"""
        user = request.user
        if user.is_authenticated:
            # 用户已登录查询redis购物车
            redis_conn = get_redis_connection('carts')
            # 获取Redis中的购物车数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 获取redis的选中状态
            # cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis中的数据构造成跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for foods_id, count in redis_cart.items():
                cart_dict[int(foods_id)] = {
                    'count': int(count),
                    # 'selected': foods_id in cart_selected
                }
        else:
            # 用户未登录，查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转为字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
        # 构造购物车渲染数据
        foods_ids = cart_dict.keys()
        foods = FoodsChannel.objects.filter(id__in=foods_ids)
        cart_skus = []
        total = 0
        for food in foods:
            cart_skus.append({
                'id': food.id,
                'name': food.name,
                'count': cart_dict.get(food.id).get('count'),
                # 'selected': str(cart_dict.get(food.id).get('selected')),  # 将True,转为“True”，方便json解析
                'url': food.url,
                'price': str(food.price),  # 从Decimal('10.2')中取出‘10.2’，方便json解析
                'amount': str(food.price * cart_dict.get(food.id).get('count')),
            })

            total+=int(food.price * cart_dict.get(food.id).get('count'))
            print(total)
            # print(food.id)
            # print(food.price)
            # print(food.price * cart_dict.get(food.id).get('count'))
        addresses = Address.objects.filter(is_deleted=False)
        context = {
            'cart_skus': cart_skus,
            'addresses':addresses,
            'total':total,
        }
        return render(request,'shop_cart.html',context)

    def post(self, request):
        """添加购物车"""
        # 获取参数
        # json_dict = json.loads(request.body.decode())
        # food_id = json_dict.get('food_id')
        # food_id = int(request.body.decode()[3:])
        # count = int(request.body.decode()[-1])
        food = request.body.decode().split('&')
        food_id = int(food[0][3:])
        count= int(food[1][6:])
        print(food_id)
        print(count)

        # 校验参数
        if not all([food_id,count]):
            return http.HttpResponseBadRequest('缺少参数')
        # 判断sku_id是否存在
        try:
            FoodsChannel.objects.get(id=food_id)
        except FoodsChannel.DoesNotExist:
            return http.HttpResponseBadRequest('商品不存在')

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseBadRequest('参数count有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 新增购物车数据
            pl.hincrby('carts_%s' % user.id, food_id,count)
            # 执行管道
            pl.execute()
            # 响应结果
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            # 如果用户操作过cookie购物车
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:  # 用户从没有操作过cookie购物车
                cart_dict = {}

            # 判断要加入购物车的商品是否已经在购物车中,如有相同商品，累加求和，反之，直接赋值
            if food_id in cart_dict:
                # 累加求和
                origin_count = cart_dict[food_id]['count']
                count += origin_count
            cart_dict[food_id] = {
                'count': count,
            }
            # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response

    def put(self, request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        food_id = json_dict.get('food_id')
        count = json_dict.get('count')
        # print('---',food_id)
        # print('---',count)

        # 校验参数
        if not all([food_id, count]):
            return http.HttpResponseBadRequest('缺少必传参数')
        # 判断sku_id是否存在
        try:
            food = FoodsChannel.objects.get(id=food_id)
        except FoodsChannel.DoesNotExist:
            return http.HttpResponseBadRequest('do not found sku_id')

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseBadRequest('参数count有误')

        # 验证用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录 修改redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 已登录直接覆盖
            sk = pl.hget('carts_%s' % user.id,food_id)
            print(sk)
            pl.hset('carts_%s' % user.id, food_id, int(count))
            pl.execute()

            # 创建响应对象
            cart_sku = {
                'id': food_id,
                'count': count,
                'name': food.name,
                'url': food.url,
                'price': food.price,
                'amount': food.price * count,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        else:
            # 用户未登录 修改cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            # 直接覆盖
            cart_dict[food_id] = {
                'count': count,
            }
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 响应对象
            cart_sku = {
                'id': food_id,
                'count': count,
                'name': food.name,
                'url': food.url,
                'price': food.price,
                'amount': food.price * count,
            }
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入cookie
            response.set_cookie('carts', cookie_cart_str, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response

    def delete(self, request):
        """删除购物车"""
        # 校验参数
        json_dict = json.loads(request.body.decode())
        food_id = json_dict.get('food_id')
        print(food_id)
        # 判断sku_id是否存在
        try:
            FoodsChannel.objects.get(id=food_id)
        except FoodsChannel.DoesNotExist:
            return http.HttpResponseBadRequest('not found sku_id')

        # 验证用户是否登录
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除键，就等于删除了整个记录
            pl.hdel('carts_%s' % user.id, food_id)
            pl.execute()

            # 删除结束后没有响应数据，响应状态码就可以了
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车记录成功'})
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if food_id in cart_dict:
                del cart_dict[food_id]
                cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cookie_cart_str, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response